import Vue from "vue"
import Vuex from "vuex"
Vue.use(Vuex)

const store = new Vuex.Store({
    state: {
        carList: []
    },
    mutations: {

        pushCarList(state, payload) {
            payload.count = 1;
            payload.check = true;
            // const old_payload = JSON.parse(JSON.stringify(payload));
            state.carList.push(payload);



        },

        increCount(state, payload) {

            payload.count++;

        }

        // setCarList(state, payload) {
        //     const old_payload = state.carList.find((item) => item.iid === payload.iid);
        //     if (old_payload) {
        //         commit('increCount', old_payload);

        //     }
        //     else {
        //         // commit('pushCarList', payload);
        //         state.carList.push(payload);
        //     }
        //     console.log(payload);
        // }

    },
    getters: {
        getListLength(state) {

            return state.carList.length

        }

    },
    actions: {
        setCarList(context, payload) {

            return new Promise((resolve, reject) => {
                const old_payload = context.state.carList.find((item) => item.id === payload.id);

                if (old_payload) {
                    context.commit('increCount', old_payload);
                    resolve('当前商品数量加1');

                }
                else {
                    context.commit('pushCarList', payload);
                    resolve('添加新的商品');
                }
            })


        },
    }

})


export default store;
